﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Stertex.Service;
using Stertex.Repository;
using Stertex.Common;

namespace Stertex.Service
{
    public class UserService : ServiceCore<Repository.User>
    {
        public Repository.User RegisterNewUser(User user, Profile profile)
        {
            ServiceCore<Profile> profileService = new ServiceCore<Profile>();
            profile = profileService.Add(profile);
            user.ProfileID = profile.ProfileID;
           user= Add(user);
            UnitOfWork.Commit();
            return user;
        }

        public ExecuteCodes ActivateAccountByKey(string Key)
        {
            if (string.IsNullOrEmpty(Key)) return ExecuteCodes.InvaidOperation;

            var user = GetUserByKey(Key);
            
            if(user == null) return ExecuteCodes.AccountNotFoundOrExpired;

            if(user.Status == UserStatus.Activated){
                return ExecuteCodes.AccountAlreadyActivated;
            }

            user.Status = UserStatus.Activated;
            UnitOfWork.Commit();

            return ExecuteCodes.Successful;
        }

        public void UpdatePassword(string Key, string Password)
        {
            var user = GetUserByKey(Key);
            user.Password = SecurityHelper.HashPassword(Password);
            UnitOfWork.Commit();
        }

        public User GetUserByKey(string Key)
        {
            string email = SecurityHelper.Decrypt(Key);

            var user = FirstOrDefault(p => p.Email == email);
            return user;
        }

        public bool  ValidateUser(string username, string password)
        {
            string hashed = SecurityHelper.HashPassword(password);

            var user = FirstOrDefault(p => p.Email == username && p.Status == UserStatus.Activated && p.Password == hashed);
            return user != null;
        }

        public User GetByEmail(string email)
        {
            return FirstOrDefault(p => p.Email == email);
        }



        public void CreateProfile(int userId, Profile profile)
        {
            ServiceCore<Profile> ps = new ServiceCore<Profile>();

            profile.Owners.Add(new Owner() {
                OwnerID = userId,
                OwnerRelTypeID = 1
                
            });
            profile = ps.Add(profile);
            //ServiceCore<Owner> os = new ServiceCore<Owner>();
            //os.Add(new Owner() {
            //    OwnerID = userId,
            //    ProfileID = profile.ProfileID,
            //    OwnerRelTypeID = 1
            //});
            UnitOfWork.Commit();
        }
    }
}
